#region License

/*
  GShield - Game Shield
  Copyright (C) 2006-2007 WaveTech Digital Technologies, Inc.
                                http://www.wtdt.com

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#endregion License

#region Includes

using System.Collections.Generic;
using System.Linq;

#endregion

namespace WaveTech.GShield.Data
{
	public static class BannedDAO
	{
		public static bool IsGameBanned(int gameId)
		{
			var policy = from p in Database.DC.BannedPolicies
			             where p.GameId == gameId && p.Username == "SYSTEM"
			             select p;

			if (policy != null)
				return true;
			else
				return false;
		}

		public static bool IsGameBanned(int gameId, string username)
		{
			var policy = from p in Database.DC.BannedPolicies
			             where p.GameId == gameId && p.Username == username
			             select p;

			if (policy != null)
				return true;
			else
				return false;
		}

		public static BannedPolicy GetBannedPolicyByGameUser(int gameId, string username)
		{
			var policy = from p in Database.DC.BannedPolicies
			             where p.GameId == gameId && p.Username == username
			             select p;

			return policy.Single();
		}

		public static List<string> GetUsersListForGame(int gameId)
		{
			var names = from p in Database.DC.BannedPolicies
			            where p.GameId == gameId
			            select p.Username;

			return names.ToList();
		}

		public static void Delete(int policyId)
		{
			var policy = from p in Database.DC.BannedPolicies
			             where p.Id == policyId
			             select p;

			Database.DC.BannedPolicies.DeleteAllOnSubmit(policy);
			Database.DC.SubmitChanges();
		}

		public static void Insert(BannedPolicy policy)
		{
			Database.DC.BannedPolicies.InsertOnSubmit(policy);
			Database.DC.SubmitChanges();
		}

		public static List<string> GetAllBannedPolicyUsers()
		{
			var names = from p in Database.DC.BannedPolicies
			            select p.Username;

			return names.ToList();
		}
	}

	#region Old BannedDAO

	/*
  /// <summary>
  /// Banned Data Access Objects
  /// </summary>
  public class BannedDAO
  {
    #region Is Game Banned
    /// <summary>
    /// Checks the database to see if a game, by it's Id, is banned
    /// </summary>
		/// <param name="gameId">GameId to check</param>
    /// <returns>True if the game is banned, otherwise False</returns>
    public bool? IsGameBanned(int? gameId)
    {
			if (gameId == null)
        throw new ArgumentNullException("id");

      Database db;
      DbCommand dbCommand;
      
      db = DatabaseFactory.CreateDatabase();
    	dbCommand = 
				db.GetSqlStringCommand(@"SELECT Id
																	FROM dbo.BannedPolicy
																	WHERE (GameId = @Id)");

			db.AddInParameter(dbCommand, "@Id", DbType.Int32, gameId);

      object o = db.ExecuteScalar(dbCommand);

      if (o == null)
        return false;
      else
        return true;
    }

    public bool? IsGameBanned(int? id, string userId)
    {
      if (id == null)
        return null;

      if (userId == null)
        userId = "SYSTEM";

			if (GetBannedPolicy(id, userId) == null)
        return false;
      else
        return true;
    }
    #endregion Is Game Banned

    #region Does Banned Policy Exist
    /// <summary>
    /// Checks to see if a Banned Policy exists by it's Id
    /// </summary>
    /// <param name="id">BannedPolicyId to check</param>
    /// <returns>True if BannedPolicy exists, otherwise False</returns>
    public bool DoesBannedPolicyExist(int? id)
    {
      if (id == null)
        throw new ArgumentNullException("id");

      Database db;
      DbCommand dbCommand;
      
      db = DatabaseFactory.CreateDatabase();
      dbCommand = db.GetSqlStringCommand(@"SELECT Id, Username, GameId, DateBanned
																						FROM dbo.BannedPolicy
																						WHERE (Id = @Id)");

      db.AddInParameter(dbCommand, "@Id", DbType.Int32, id);

      object o = db.ExecuteScalar(dbCommand);

      if (o == null)
        return false;
      else
        return true;
    }
    #endregion Does Banned Policy Exist

    #region Get Banned Policy
    /// <summary>
    /// Gets a BannedPolicy from the database by it's Id
    /// </summary>
    /// <param name="id">BannedPolicyId to retrieve</param>
    /// <returns>Populated Banned Policy object</returns>
    public BannedPolicy GetBannedPolicy(int? id)
    {
      if (id == null)
        throw new ArgumentNullException("id");

      Database db;
      DbCommand dbCommand;
      
      db = DatabaseFactory.CreateDatabase();
			dbCommand = db.GetSqlStringCommand(@"SELECT Id, Username, GameId, DateBanned
																						FROM dbo.BannedPolicy
																						WHERE (Id = @Id)");

      db.AddInParameter(dbCommand, "@Id", DbType.Int32, id);

      return FillBannedPolicyObject(db.ExecuteReader(dbCommand));
    }

    /// <summary>
    /// Gets a BannedPolicy from the database by GameId and UserName
    /// </summary>
    /// <param name="gameId">GameId to get the policy for</param>
    /// <param name="userName">UserName to get the policy for, if Null a SYSTEM policy is used</param>
    /// <returns>Populated BannedPolicy object</returns>
    public BannedPolicy GetBannedPolicy(int? gameId, string userName)
    {
      if (gameId == null)
        throw new ArgumentNullException("gameId");

      if (userName == null)
        userName = "SYSTEM";
      
      Database db = DatabaseFactory.CreateDatabase();
			DbCommand dbCommand = db.GetSqlStringCommand(@"SELECT Id, Username, GameId, DateBanned
																											FROM dbo.BannedPolicy
																											WHERE (GameId = @Id) AND (Username = @UserId)");

      db.AddInParameter(dbCommand, "@Id", DbType.Int32, gameId);
      db.AddInParameter(dbCommand, "@UserId", DbType.String, userName);

      return FillBannedPolicyObject(db.ExecuteReader(dbCommand));
    }
    #endregion Get Banned Policy

    #region Get Games List
    /// <summary>
    /// Gets a list of Games from the database
    /// </summary>
    /// <returns>String array of Game names</returns>
    public string[] GetGamesList()
    {
      Database db;
      DbCommand dbCommand;
      ArrayList lst;
      string[] data;

        db = DatabaseFactory.CreateDatabase();
        dbCommand = db.GetSqlStringCommand(@"SELECT Games.Name
																							FROM BannedPolicy
																							INNER JOIN Games
																							ON BannedPolicy.GameId = Games.Id");

        lst = new ArrayList();
        IDataReader r = db.ExecuteReader(dbCommand);

        while (r.Read())
        {
          lst.Add(r[0].ToString());
        }

        data = new string[lst.Count];

        for (int i = 0; i < lst.Count; i++)
        {
          data[i] = lst[i].ToString();
        }

      return data;
    }
    #endregion Get Games List

    #region Save
    /// <summary>
    /// Saves or Updates a BannedPolicy to the database
    /// </summary>
    /// <param name="bannedPolicy">BannedPolicy object to Save or Update</param>
    /// <returns>Popualted BannedPolicy object</returns>
    public BannedPolicy Save(BannedPolicy bannedPolicy)
    {
      if (bannedPolicy == null)
        throw new ArgumentNullException("bannedPolicy");

      if (bannedPolicy.Id == null)
        bannedPolicy = Insert(bannedPolicy);
      else
        bannedPolicy = Update(bannedPolicy);

      return bannedPolicy;
    }
    #endregion Save

    #region Insert
    /// <summary>
    /// Inserts a BannedPolicy into the database
    /// </summary>
    /// <param name="bannedPolicy">BannedPoliy object to save</param>
    /// <returns>Populated BannedPolicy Object</returns>
    private BannedPolicy Insert(BannedPolicy bannedPolicy)
    {
      if (bannedPolicy == null)
        throw new ArgumentNullException("bannedPolicy");
      else if (bannedPolicy.Id != null)
        throw new ArgumentException("BannedPolicy.Id must be null to perform an insert.");
      
      Database db;
      DbCommand dbCommand;
      
        db = DatabaseFactory.CreateDatabase();
				dbCommand = db.GetSqlStringCommand(@"INSERT INTO [BannedPolicy]
																						([Username]
																						,[GameId]
																						,[DateBanned])
																						VALUES
																						(@Username
																						,@GameId
																						,@DateBanned)
	
																						SELECT Scope_Identity()");

        db.AddInParameter(dbCommand, "@UserName", DbType.String, bannedPolicy.UserName);
        db.AddInParameter(dbCommand, "@GameId", DbType.Int32, bannedPolicy.GameId);
        db.AddInParameter(dbCommand, "@DateBanned", DbType.DateTime, bannedPolicy.DateBanned);

        bannedPolicy.Id = int.Parse(db.ExecuteScalar(dbCommand).ToString());

      return bannedPolicy;
    }
    #endregion Insert

    #region Update
    /// <summary>
    /// Updates a BannedPolicy object in the database
    /// </summary>
    /// <param name="bannedPolicy">BannedPolicy object to Update</param>
    /// <returns>Copy of the presisted BannedPolicy object</returns>
    private BannedPolicy Update(BannedPolicy bannedPolicy)
    {
      if (bannedPolicy == null)
        throw new ArgumentNullException("bannedPolicy");
      else if (bannedPolicy.Id == null)
        throw new ArgumentException("BannedPolicy.Id must not be null to perform an update.");
      
      Database db;
      DbCommand dbCommand;

        db = DatabaseFactory.CreateDatabase();
        dbCommand = db.GetSqlStringCommand(@"UPDATE [BannedPolicy]
																							SET [Username] = @Username
																							,[GameId] = @GameId
																							,[DateBanned] = @DateBanned
																							WHERE (Id = @Id)");

        db.AddInParameter(dbCommand, "@UserName", DbType.String, bannedPolicy.UserName);
        db.AddInParameter(dbCommand, "@GameId", DbType.Int32, bannedPolicy.GameId);
        db.AddInParameter(dbCommand, "@DateBanned", DbType.DateTime, bannedPolicy.DateBanned);
        db.AddInParameter(dbCommand, "@Id", DbType.Int32, bannedPolicy.Id);

        db.ExecuteNonQuery(dbCommand);

      return bannedPolicy;
    }
    #endregion Update

    #region Delete
    /// <summary>
    /// Deletes a BannedPolicy object by it's Id
    /// </summary>
    /// <param name="id">BannedPolicy.Id to delete</param>
    public void Delete(int? id)
    {
      if (id == null)
        throw new ArgumentNullException("id");
      
      Database db;
      DbCommand dbCommand;

        db = DatabaseFactory.CreateDatabase();
				dbCommand = db.GetSqlStringCommand(@"DELETE
																							FROM dbo.BannedPolicy
																							WHERE (Id = @Id)");

        db.AddInParameter(dbCommand, "@Id", DbType.Int32, id);

        db.ExecuteScalar(dbCommand);
    }
    #endregion Delete

		#region Get Banned Policy Users
		/// <summary>
		/// Returns a list of all users who have a Banned Game Policy
		/// </summary>
		/// <returns>String array of users with a Banned Game Policy</returns>
		public string[] GetBannedPolicyUsers()
		{
			Database db;
			DbCommand dbCommand;
			ArrayList lst;

			db = DatabaseFactory.CreateDatabase();
			dbCommand = db.GetSqlStringCommand(@"SELECT [Username]
																						FROM BannedPolicy");

			lst = new ArrayList();
			IDataReader r = db.ExecuteReader(dbCommand);

			while (r.Read())
			{
				lst.Add(r[0].ToString());
			}

			return (string[])lst.ToArray(typeof(string));
		}
		#endregion Get Banned Policy Users

		#region Get Users List For Game
		/// <summary>
    /// Gets a list of banned users for a specific gameId
    /// </summary>
    /// <param name="gameId">GameId to get the users for</param>
    /// <returns>String array of banned users for a Game</returns>
    public string[] GetUsersListForGame(int? gameId)
    {
      if (gameId == null)
        throw new ArgumentNullException("gameId");
      
      Database db;
      DbCommand dbCommand;
      ArrayList lst;
      string[] data;

        db = DatabaseFactory.CreateDatabase();
				dbCommand = db.GetSqlStringCommand(@"SELECT Username
																							FROM dbo.BannedPolicy
																							WHERE ([GameId] = @GameId)");

        db.AddInParameter(dbCommand, "@GameId", DbType.Int32, gameId);

        lst = new ArrayList();
        IDataReader r = db.ExecuteReader(dbCommand);

        while (r.Read())
        {
          lst.Add(r[0].ToString());
        }

        data = new string[lst.Count];

        for (int i = 0; i < lst.Count; i++)
        {
          data[i] = lst[i].ToString();
        }

      return data;
    }
    #endregion Get Users List For Game

    #region Fill Banned Policy Object
    /// <summary>
    /// Populates a BannedPolicy object froma  DataReader
    /// </summary>
    /// <param name="reader">DataReader to populate with</param>
    /// <returns>Populated BannedPolicy object</returns>
    private BannedPolicy FillBannedPolicyObject(IDataReader reader)
    {
      if (reader == null)
        throw new ArgumentNullException("reader");

      BannedPolicy policy = null;

      if (reader.Read())
      {
        policy = new BannedPolicy();

        if (!reader.IsDBNull(reader.GetOrdinal("Id")))
          policy.Id = reader.GetInt32(reader.GetOrdinal("Id"));

        if (!reader.IsDBNull(reader.GetOrdinal("GameId")))
          policy.GameId = reader.GetInt32(reader.GetOrdinal("GameId"));

        if (!reader.IsDBNull(reader.GetOrdinal("DateBanned")))
          policy.DateBanned = reader.GetDateTime(reader.GetOrdinal("DateBanned"));
      }

      return policy;
    }
    #endregion Fill Banned Policy Object
  }
    */

	#endregion  Old BannedDAO
}